var Router = require('koa-router')
var DB = require('../module/db')

var userRouter = new Router()

// 配置路由
userRouter.get('/', async (ctx) => {
    var result = await DB.find('user', {})
    await ctx.render('artIndex', {list: result})
})

userRouter.get('/add', async (ctx) => {
    await ctx.render('add')
})

userRouter.post('/doAdd', async (ctx) => {
    let addData = ctx.request.body
    const result = await DB.insert('user', addData)
    try {
        if (result.result.ok) {
            ctx.redirect('/user')
        }
    } catch (error) {
        ctx.redirect('/user/add')
    }
})

userRouter.get('/edit', async (ctx) => {
    // 根据 id 获取用户信息
    let userId = ctx.query.id
    const result = await DB.find('user', { "_id": DB.getObjectId(userId) })
    await ctx.render('edit', {list: result[0]})
})

userRouter.post('/doEdit', async (ctx) => {
    let userData = ctx.request.body
    var  id = userData.id
    var username = userData.username
    var age = userData.age
    var sex = userData.sex
    var status = userData.status
    const result = await DB.update('user', {"_id": DB.getObjectId(id)}, { username, age, sex, status })
    try {
        if (result.result.ok) {
            ctx.redirect('/user')
        }
    } catch (error) {
        ctx.redirect('/user/add')
    }
})
userRouter.get('/delete', async (ctx) => {
    let id = ctx.query.id
    const result = await DB.remove('user', { "_id": DB.getObjectId(id) })
    try {
        if (result.result.ok) {
            ctx.redirect('/user')
        }
    } catch (error) {
    }
})

module.exports = userRouter